const COOKIEPRE = "yzwcv2_";

var lock = false;

$(document).ready(reset);

function reset() {
    $("#form").hide();
    $("#show").hide();
    $("#over").hide();
    $("#fail").hide();
    if (getCookie(COOKIEPRE + "token") === "") {
        $("#submit").click(submit);
        $("#form").show();
    } else {     
        $("#award").html(awardToChinese(parseInt(getCookie(COOKIEPRE + "award"))));
        $("#id").html(getCookie(COOKIEPRE + "id"));
        var url = window.location.href + "check.php?id=" + getCookie(COOKIEPRE + "id") + "%26award=" + getCookie(COOKIEPRE + "award") + "%26name=" + escape(getCookie(COOKIEPRE + "name")) + "%26token=" + getCookie(COOKIEPRE + "token"); 
        url = "http://qr.liantu.com/api.php?text=" + url;
        $("#qr").attr("src", url);
        $("#qr").attr("alt", url);
        $("#show").show();
    }
}

function awardToChinese(award) {
    switch (award) {
        case 4:
            return "<br>“满25元减1元”代金卷一张";
        case 3:
            return "<br>贴纸两张<br>“满25元减1元”代金卷一张";
        case 2:
            return "<br>明信片一张<br>“满50元减5元”代金卷一张";
        case 1:
            return "<br>铁质书签一个<br>“满50元减5元”代金卷一张";
        case 0:
            return "<br>帆布袋(单面)一个";
    }
}

function submit() {
    if ($("#name").val() === "") {
        return;
    }
    if (lock)
        return;
    lock = true;
    $.post("./api.php",
        {
            "name": $("#name").val()
        }, deal);
}

function deal(data, status) {
    if (status !== "success") {
        lock = false;
        return;
    }
    var rsp = $.parseJSON(data);
    if (rsp.status === "success") {
        $("#form").hide();
        $("#award").html(awardToChinese(rsp.award));
        $("#id").html(rsp.id);
        var url = window.location.href + "check.php?id=" + rsp.id + "%26award=" + rsp.award + "%26name=" + rsp.name + "%26token=" + rsp.token; 
        url = "http://qr.liantu.com/api.php?text=" + url;
        $("#qr").attr("src", url);
        $("#qr").attr("alt", url);
        $("#show").show();
        return;
    }
    switch (rsp.status) {
        case "over":
            $("#fail_msg").html("抽奖已结束，感谢参与");
            break;
        case "already":
            $("#fail_msg").html("您已参与过抽奖");
            break;
        case "forbid":
            $("#fail_msg").html("访问过于频繁，请两分钟后重试");
            break;
        case "always_forbid":
            $("#fail_msg").html("您已被禁止");
            break;
        default:
            $("#fail_msg").html("未知错误");
    }
    $("#form").hide();
    $("#fail").show();
}